package dao;

import utils.ConnectionUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * @projectName: Chapter8
 * @package: dao
 * @className: baseDao
 * @author: 翟
 * @date: 2025/3/31 9:31
 */

public class BaseDao {
    private Connection connection;

    public BaseDao(Connection connection) {
        this.connection = connection;
    }

    public ResultSet executeQuery(String sql, Object... objects) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < objects.length; i++) {
            preparedStatement.setObject(i + 1, objects[i]);
        }
        return preparedStatement.executeQuery();
    }

    public int executeUpdate(String sql, Object... objects) throws SQLException {
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < objects.length; i++) {
                preparedStatement.setObject(i + 1, objects[i]);
            }
            return preparedStatement.executeUpdate();
        } finally {
            ConnectionUtil.closeALL(null, preparedStatement, null);
        }
    }
}
